package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
)

var video_path = "/home/xiefeihong/.vv/file"

type Video struct {
	Name string `uri:"filename" binding:"required"`
	Dir string `uri:"path" binding:"required"`
}

type VideoInfo struct {
	Name string `binding:"required"`
	Path string `binding:"required"`
	Size int64 `binding:"required"`
	Date time.Time `binding:"required, time_format:"2006-01-02 15:04:05"`
}

type Dir struct {
	Name string `uri:"path" binding:"required"`
}

func playVideo(c *gin.Context){
	var video Video
	if err := c.ShouldBindUri(&video); err != nil {
		c.JSON(400, gin.H{"msg": err})
		return
	}
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("inline; filename=%s", video.Name))
	c.Writer.Header().Add("Content-Type", "video/mp4")
	var filepath = fmt.Sprintf("%s/%s/%s",video_path, video.Dir ,video.Name)
	c.File(filepath)
}

func main() {
	route := gin.Default()
	route.LoadHTMLGlob("templates/*")
	route.StaticFS("/static", http.Dir("./static"))

	route.GET("/video", func(c *gin.Context) {
		dir_list, e := ioutil.ReadDir(video_path)
		if e != nil {
			fmt.Println("read dir error")
			return
		}
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"dir_list": dir_list,
		})
	})

	route.GET("/video/:path", func(c *gin.Context) {
		var dir Dir
		if err := c.ShouldBindUri(&dir); err != nil {
			c.JSON(400, gin.H{"msg": err})
			return
		}
		file_list, e := ioutil.ReadDir(fmt.Sprintf("%s/%s", video_path, dir.Name))
		if e != nil {
			fmt.Println("read dir error")
			return
		}
		var video_list[] VideoInfo
		for _, v := range file_list {
			video_list = append(video_list, VideoInfo{Name: v.Name(), Path: fmt.Sprintf("%s/%s",dir.Name ,v.Name()), Date: v.ModTime(), Size: v.Size()/1024/1024})
		}
		c.HTML(http.StatusOK, "list.tmpl", gin.H{
			"file_list": video_list,
			"page": dir.Name,
		})
	})

	route.GET("/video/:path/:filename", func(c *gin.Context) {
		playVideo(c)
	})

	route.Run(":8080")
}